package com.yupi.apispringcloudgateway.Filter;

import cn.hutool.core.collection.CollUtil;
import com.test.springbootjwtautoconfigura.JwtUtils;
import com.yupi.apiclientautocongigura.SingUtils;
import com.yupi.model.constants.RedisUserInformationConstants;
import com.yupi.model.entity.InterfaceInfo;
import com.yupi.model.entity.User;
import com.yupi.service.InnerInterfaceInfoService;
import com.yupi.service.InnerUserInterfaceInfoService;
import com.yupi.service.InnerUserService;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class CustomGlobalFilter implements GlobalFilter, Ordered {


    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;
    
    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    private final RedisTemplate redisTemplate;


    private static ArrayList<String> IP_WHITE_LIST = new ArrayList<>();

    private static final String INTERFACE_HOST = "http://localhost:8123";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1:请求日志
        final ServerHttpRequest request = exchange.getRequest();
        log.info("请求唯一标识："+request.getId());
        String path = INTERFACE_HOST+request.getPath().value().toString();
        log.info("请求路径:"+ path);
        String method = request.getMethod().toString();
        log.info("请求方法："+method);
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        log.info("请求参数："+queryParams);
        String sourceAddress = request.getLocalAddress().getHostString();
        log.info("请求地址："+sourceAddress);
        ServerHttpResponse response = exchange.getResponse();
        //2:访问控制 -黑白名单
        IP_WHITE_LIST.add("127.0.0.1");
        IP_WHITE_LIST.add("0:0:0:0:0:0:0:1");
        if(!IP_WHITE_LIST.contains(sourceAddress)){
            handleNoAuth(response);
        }

        //3:判断这个接口的来源（需要转发给user模块还是api模块）
        //todo 如果以后还有做扩展，我们也可以再写
        if(path.contains("name")){
            //说明要转发的对象是接口模块
            //4：用户鉴权
            final HttpHeaders headers = request.getHeaders();
            final String accessKey = headers.getFirst("accessKey");
            String random = headers.getFirst("random");
            String timestamp = headers.getFirst("timestamp");
            String sign = headers.getFirst("sign");
            String body = headers.getFirst("body");
            final User invokeUser = innerUserService.getInvokeUser(accessKey);
            if(invokeUser==null){
                //user==null，说明这个accessKey根本没有被分配给用户
                handleNoAuth(response);
            }
            if(Long.parseLong(random) > 10000){
                handleNoAuth(response);
            }
            //通过时间戳判断是否过期
            long currentTimeMillis = System.currentTimeMillis()/1000;
            long differenceInSeconds = (long) (currentTimeMillis/1000 - Long.parseLong(timestamp));
            if(differenceInSeconds > 300){
                handleNoAuth(response);
            }
            final String secretKey = invokeUser.getSecretKey();
            String flag = SingUtils.getSign(body, secretKey);
            if(!flag.equals(sign)){
                handleNoAuth(response);
            }
            final Long userId = invokeUser.getId();
            //5:从数据库中查询模拟接口是否存在
            InterfaceInfo interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(path,method);
            if(interfaceInfo==null){
                handleNoAuth(response);
            }
            final Long interfaceInfoId = interfaceInfo.getId();
            //6：判断接口剩余的调用次数
            final int leftnum = innerUserInterfaceInfoService.getInterfaceInfoLeftnum(interfaceInfoId, userId);
            if(leftnum <= 0){
                handleNoAuth(response);
            }
            //7:请求转化，调用模拟接口
            final Mono<Void> filter = chain.filter(exchange);
            return handleResponse(exchange,chain,interfaceInfoId,userId);
        }
        else {
            //4：判断是否需要拦截
            if(path.contains("login")){
                return chain.filter(exchange);
            }
            //5:获取token
            String token = null;
            final List<String> list = request.getHeaders().get("authorization");
            if(!CollUtil.isEmpty(list)){
                token = list.get(0);
            }
            Long userId = null;
            String userRole = null;
            //6:解析token并鉴权
            try {
                Claims claims = JwtUtils.parseJWT(token);
                userId = (Long) claims.get("id");
                userRole = (String) claims.get("userRole");
            }catch (Exception e){
                response.setStatusCode(org.springframework.http.HttpStatus.valueOf(cn.hutool.http.HttpStatus.HTTP_UNAUTHORIZED));
                return response.setComplete();
            }
            //8:放行
            return chain.filter(exchange);
        }
    }


    /**
     * 处理响应
     *
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain,Long interfaceInfoId,Long userId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    // 等调用完转发的接口后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里写数据
                            // 拼接字符串
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {
                                        // 7. 调用成功，接口调用次数 + 1 invokeCount
                                        try {
                                            innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
                                        } catch (Exception e) {
                                            throw new RuntimeException(e);
                                        }
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放掉内存
                                        // 构建日志
                                        StringBuilder sb2 = new StringBuilder(200);
                                        List<Object> rspArgs = new ArrayList<>();
                                        rspArgs.add(originalResponse.getStatusCode());
                                        String data = new String(content, StandardCharsets.UTF_8); //data
                                        sb2.append(data);
                                        // 打印日志
                                        log.info("响应结果：" + data);
                                        return bufferFactory.wrap(content);
                                    }));
                        } else {
                            // 8. 调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange); // 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }




    @Override
    public int getOrder() {
        return -1;
    }

    public Mono<Void> handleNoAuth(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.FORBIDDEN);
        //HttpStatus.FORBIDDEN 状态码403
        return response.setComplete();
    }

    public Mono<Void> handleInvokeError(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        //HttpStatus.INTERNAL_SERVER_ERROR 状态码500
        return response.setComplete();
    }
}